package com.hp.test.concurrent.producer_consumer.pc3;

import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 用阻塞队列实现生产者消费者
 *
 * @author hupan
 * @date 2021-05-03 14:10
 */
public class ProducerAndConsumer3 {

    public static void main(String[] args) {
        Storage storage = new Storage();
        Producer producer = new Producer("生产者", storage);
        Consumer consumer = new Consumer("消费者", storage);

        new Thread(producer).start();
        new Thread(consumer).start();
    }

}


@Getter
class Storage {
    // 仓库最大存储量
    private final int MAX_SIZE = 3;
    // 仓库存储的载体
    private final LinkedBlockingQueue<Object> list = new LinkedBlockingQueue<>(3);

    // 生产产品
    public void produce(String producer) {
        // 如果仓库已满
        if (list.size() == MAX_SIZE) {
            System.out.println("仓库已满，【" + producer + "】： 暂时不能执行生产任务!");
        }

        // 生产产品
        try {
            list.put(new Object());
            System.out.println("【" + producer + "】：生产了一个产品\t【现仓储量为】:" + list.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 消费产品
    public void consume(String consumer) {
        // 如果仓库存储量不足
        if (list.size() == 0) {
            System.out.println("仓库已空，【" + consumer + "】： 暂时不能执行消费任务!");
        }

        try {
            list.take();
            System.out.println("【" + consumer + "】：消费了一个产品\t【现仓储量为】:" + list.size());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}


@Getter
@Setter
class Producer extends Thread {
    private String producer;
    private Storage storage;

    public Producer(String producer, Storage storage) {
        this.producer = producer;
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            storage.produce(producer);
            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


@Getter
@Setter
class Consumer extends Thread {
    private String consumer;
    private Storage storage;

    public Consumer(String consumer, Storage storage) {
        this.consumer = consumer;
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            storage.consume(consumer);
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}



